package db_main

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"longmen/server/config/global"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/models/models_main"
	"time"

	"github.com/go-sql-driver/mysql"
)

func InsertDownloadTimes(deviceId, source string, sem int) error {
	o := &models_main.AppDownload{
		DeviceId: deviceId,
		Source:   source,
		Time:     time.Now(),
		Sem:      sem,
	}

	var mysqlErr *mysql.MySQLError
	err := global.GetR().Create(&o).Error
	if errors.As(err, &mysqlErr) && mysqlErr.Number == 1062 {
		err = nil
	}

	if err != nil {
		err = fmt.Errorf("%s%s", util.Convert2(), err.Error())
		return err
	}

	return nil
}

func GetDownloadTime(deviceId string) (int64, error) {
	if deviceId == "" {
		return 0, nil
	}
	var d models_main.AppDownload
	err := global.GetR().Where("device_id = ?", deviceId).First(&d).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return 0, nil
		}
		return 0, err
	}
	return d.Time.Unix(), nil
}
